package com.fuyd.pms.background.web.account;

import com.fuyd.pms.entity.account.MerchantUser;
import com.fuyd.pms.background.service.account.AccountService;
import com.fuyd.pms.background.web.base.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

/**
 * 用户个人资料相关的Controller
 * Created by fuyongde on 2016/1/3.
 */
@Controller
@RequestMapping(value = "/account")
public class ProfileController extends BaseController {

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 用户的个人资料的页面
     *
     * @return
     */
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String profile(Model model) {
        MerchantUser merchantUser = getCurrentUser();
        model.addAttribute("merchantUser", accountService.findById(merchantUser.getId()));
        return "account/profile";
    }

    /**
     * 修改用户个人资料的页面
     *
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model) {
        MerchantUser merchantUser = getCurrentUser();
        model.addAttribute("merchantUser", merchantUser);
        return "account/update";
    }

    /**
     * 用户个人资料修改的操作
     *
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String doUpdate(
            @Valid @ModelAttribute("merchantUser") MerchantUser merchantUser,
            Model model
    ) {
        accountService.update(merchantUser);
        return "redirect:/account/profile";
    }

    /**
     * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
     */
    @ModelAttribute
    public void getTask(@RequestParam(value = "id", defaultValue = "") String id, Model model) {
        if (StringUtils.isNotEmpty(id)) {
            model.addAttribute("merchantUser", accountService.findById(id));
        }
    }
}
